import Cookie from 'js-cookie' // 操作cookie
export default {
  state: {
    isCollapse: false, // 菜单折叠状态
    menu: [], // 全部菜单，后台返回的菜单路由对象
    currentMenu: '', // 当前点击的菜单
    tabList: [
      // 点击添加到标签
      {
        path: '/',
        name: 'home',
        label: '首页',
        icon: 's-home'
      }
    ]
  },
  mutations: {
    setMenu(state, data) {
      // 存储动态路由
      state.menu = data
      Cookie.set('menu', JSON.stringify(data)) // Cookie只能是字符串
    },
    clearMenu(state) {
      // 删除Cookie
      state.menu = []
      Cookie.remove('menu')
    },
    addMenu(state, router) {
      // 获取动态路由
      if (!Cookie.get('menu')) {
        // 如果menu不存在将不执行下边的语句
        return
      }
      let menu = JSON.parse(Cookie.get('menu')) // 转为对象
      state.menu = menu
      let currentMenu = [
        {
          path: '/',
          component: () => import('@/views/pages/Main'),
          children: []
        }
      ]
      menu.forEach(item => {
        if (item.children) {
          item.children = item.children.map(item => {
            item.component = () => import(`@/views/pages/${item.url}`)
            return item
          })
          // es6扩展运算符...  代表就是把数据全部展开
          currentMenu[0].children.push(...item.children)
        } else {
          item.component = () => import(`@/views/pages/${item.url}`)
          currentMenu[0].children.push(item)
        }
      })
      router.addRoutes(currentMenu)
    },

    // findIndex是寻找其下标
    selectMenu(state, data) {
      // 左右导航联动
      if (!(data.name == 'home')) {
        state.currentMenu = data
        let result = state.tabList.findIndex(item => item.name == data.name)
        result == -1 ? state.tabList.push(data) : ''
        Cookie.set('tagList', JSON.stringify(state.tabList))
        Cookie.set('current', JSON.stringify(state.currentMenu))
      } else {
        state.currentMenu = null
        Cookie.remove('current')
      }
      // data.name == 'home' ? (state.currentMenu = null) : (state.currentMenu = data)
    },
    getMenu(state) {
      // 获取tagList
      if (Cookie.get('tagList')) {
        let tagList = JSON.parse(Cookie.get('tagList'))
        state.tabList = tagList
      }
    },
    getCurrent(state) {
      // current
      if (Cookie.get('current')) {
        let current = JSON.parse(Cookie.get('current'))
        state.currentMenu = current
      }
    },
    closeTab(state, data) {
      // 关闭标签
      let result = state.tabList.findIndex(item => item.name == data.name)
      state.tabList.splice(result, 1)
      Cookie.set('tagList', JSON.stringify(state.tabList))
    },
    change_collapseMenu(state) {
      //侧边栏动画显示隐藏
      state.isCollapse = !state.isCollapse
    }
  },
  actions: {
    collapseMenu(ctx) {
      ctx.commit('change_collapseMenu')
    }
  },
  getters: {}
}
